﻿using AJWPFAdmin.Core.Components.AJTable.ViewModels;
using AJWPFAdmin.Core.Enums;
using AJWPFAdmin.Core.Utils;
using AJWPFAdmin.Services.EF;
using MaterialDesignExtensions.Controls;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static AJWPFAdmin.Core.ExceptionTool;
using System.Windows.Controls;
using Masuit.Tools.Models;
using EntranceGuardManager.Modules.Main.Views;
using AJWPFAdmin.Services;
using AJWPFAdmin.Core.Models.EF.Tables;
using AJWPFAdmin.Services.EF.TableExts;
using System.Runtime.Serialization;
using AJWPFAdmin.Core.Models;
using AJWPFAdmin.Core.Validation;
using Yitter.IdGenerator;

namespace EntranceGuardManager.Modules.Main.ViewModels
{

    public class SystemDictionaryListViewModel : BindableBase, INavigationAware
    {
        private SystemDictionaryExt.SystemDictionaryKey _navParamType;

        private AJTableFetchOptions _fetchOptions;

        public AJTableFetchOptions FetchOptions
        {
            get
            {
                return _fetchOptions;
            }
            set
            {
                SetProperty(ref _fetchOptions, value);
            }
        }

        private AJTableImportOptions _importOptions;
        public AJTableImportOptions ImportOptions
        {
            get { return _importOptions; }
            set { SetProperty(ref _importOptions, value); }
        }

        private List<AJTableColumnItem> _columns;

        public List<AJTableColumnItem> Columns
        {
            get { return _columns; }
            set { SetProperty(ref _columns, value); }
        }

        private AJTableSearchFormConfig _formConfig;

        public AJTableSearchFormConfig FormConfig
        {
            get { return _formConfig; }
            set { SetProperty(ref _formConfig, value); }
        }

        private DelegateCommand<DataGridRow> _loadingRowCmd;
        public DelegateCommand<DataGridRow> LoadingRowCmd =>
            _loadingRowCmd ?? (_loadingRowCmd = new DelegateCommand<DataGridRow>(ExecuteLoadingRowCmd));

        void ExecuteLoadingRowCmd(DataGridRow row)
        {

        }

        private DelegateCommand<SystemDictionary> _editCmd;
        public DelegateCommand<SystemDictionary> EditCmd =>
            _editCmd ?? (_editCmd = new DelegateCommand<SystemDictionary>(ExecuteEditCmd));

        void ExecuteEditCmd(SystemDictionary parameter)
        {
            var @params = new DialogParameters
            {
                { "data", parameter },
                { "type", _navParamType },
            };
            _dialogSvc.ShowDialog(nameof(SystemDictionaryForm), @params, r =>
            {
                if (r.Result == ButtonResult.OK)
                {
                    FetchOptions.RequestRefresh(false);
                }
            });
        }


        private DelegateCommand<SystemDictionary> _deleteCmd;
        public DelegateCommand<SystemDictionary> DeleteCmd =>
            _deleteCmd ?? (_deleteCmd = new DelegateCommand<SystemDictionary>(ExecuteDeleteCmd));

        async void ExecuteDeleteCmd(SystemDictionary parameter)
        {
            var confirm = await CommonUtil.ShowConfirmDialogAsync(new ConfirmationDialogArguments
            {
                Title = "删除确认",
                Message = $"即将删除 {parameter.Name} ?"
            });

            if (confirm)
            {
                db.SystemDictionaries.Remove(parameter);
                await db.SaveChangesAsync();

                FetchOptions.RequestRefresh(false);
            }
        }

        private IDialogService _dialogSvc;
        private DbService db;

        public SystemDictionaryListViewModel(DbService dbIns,
            IEventAggregator eventAggregator,
            IDialogService dialogSvc)
        {

            _dialogSvc = dialogSvc;
            //eventAggregator.GetEvent<AJGlobalExceptionResolvedEvent>().Subscribe(() => Loading = false);

            ImportOptions = new AJTableImportOptions
            {
                ImportType = typeof(SystemDictionary),
                TemplateRowsHandler = () =>
                {
                    return new List<object> {
                        new SystemDictionary
                        {
                            Code = "001",
                            Name = _navParamType == SystemDictionaryExt.SystemDictionaryKey.货车 ? "大型货车" : "97",
                        }
                    };
                },
                ImportDataItemProcessHandler = (item) =>
                {
                    var result = new ProcessResult();

                    var parentId = (long)_navParamType;

                    if (item is not SystemDictionary model)
                    {
                        result.SetError($"实体数据转换失败");
                        return result;
                    }
                    var checkRet = FormChecker.RequireAndLength(model.Code, 20, "编号");
                    if (!checkRet.Success)
                    {
                        result.SetError(checkRet.Message);
                        return result;
                    }
                    checkRet = FormChecker.RequireAndLength(model.Name, 20, "名称");
                    if (!checkRet.Success)
                    {
                        result.SetError(checkRet.Message);
                        return result;
                    }

                    var code = model.Code;
                    var name = model.Name;

                    if (db.SystemDictionaries.Any(p => p.Code == code && p.ParentId == parentId))
                    {
                        result.SetError($"{code} 已存在");
                        return result;
                    }

                    if (db.SystemDictionaries.Any(p => p.Name == name && p.ParentId == parentId))
                    {
                        result.SetError($"{name} 已存在");
                        return result;
                    }

                    var record = new SystemDictionary
                    {
                        Id = YitIdHelper.NextId(),
                        Code = code,
                        Name = name,
                        ParentId = parentId,
                        CreateDate = DateTime.Now
                    };

                    db.SystemDictionaries.Add(record);

                    result.SetSuccess();

                    return result;
                },
                ImportCompleteHandler = async () =>
                {
                    var result = new ProcessResult();
                    result.SetSuccess();
                    await db.SaveChangesAsync();
                    return result;
                }
            };

            FetchOptions = new AJTableFetchOptions
            {
                FetchOnLoaded = false,
                //ExportFileName = "车辆记录导出",
                Handle = async (formCfg, pageCfg) =>
                {

                    var name = FormConfig.Schemas
                .FirstOrDefault(p => p.Field == nameof(SystemDictionary.Name)).Value?.ToString();

                    var pid = (long)_navParamType;

                    var list = await db.SystemDictionaries.LikeOrLike(name, p => p.Name, p => p.Code)
                        .Where(p => p.ParentId == pid)
                        .OrderBy(p => p.SortNo).ThenBy(p => p.Id)
                        .ToPagedListAsync(pageCfg.Current, pageCfg.PageSize);

                    return new AJTableFetchResult
                    {
                        Total = list.TotalCount,
                        HasNext = list.HasNext,
                        Rows = list.Data
                    };
                }
            };

            FormConfig = new AJTableSearchFormConfig
            {
                Schemas = new ObservableCollection<AJTableSearchFormSchema>
                {
                    new AJTableSearchFormSchema
                    {
                        Label = "名称/编号",
                        Field = nameof(SystemDictionary.Name),
                        Type = AJTableSchemaType.Input,
                        IsPopular = true,
                    },
                    //new AJTableSearchFormSchema
                    //{
                    //    Labels = new string[]{ "创建开始日期","创建结束日期" },
                    //    Field = nameof(SystemDictionary.CreateDate),
                    //    Type = AJTableSchemaType.RangePicker,
                    //    Value = new ObservableCollection<DateTime?>( new DateTime?[2]{null,null}),
                    //    IsPopular = true,
                    //},
                },
                AdvFilterVisibility = System.Windows.Visibility.Collapsed,
                ExportVisibility = System.Windows.Visibility.Collapsed,
            };

            Columns = new List<AJTableColumnItem>
            {
                new AJTableColumnItem
                {
                    Title = "操作",
                    CustomTemplate = new AJTableCustomTemplate
                    {
                        Key = "TableOperatioin"
                    },
                    Fixed = AJTableColumnFixedType.Right,
                    Width = new DataGridLength(160),
                },
                new AJTableColumnItem
                {
                    DataIndex = nameof(SystemDictionary.Code),
                    Title = "编号"
                },
                new AJTableColumnItem
                {
                    DataIndex = nameof(SystemDictionary.Name),
                    Title = "名称",
                },
                new AJTableColumnItem
                {
                    DataIndex = nameof(SystemDictionary.SortNo),
                    Title = "序号"
                },
                new AJTableColumnItem
                {
                    DataIndex = nameof(SystemDictionary.CreateDate),
                    Title = "创建日期",
                    Formatter = new AJTableColumnFormatter
                    {
                        Handler = (val) =>
                        {
                            return ((DateTime)val).ToString("yyyy-MM-dd HH:mm:ss");
                        }
                    }
                }
            };
            db = dbIns;
        }

        public async void OnNavigatedTo(NavigationContext navigationContext)
        {
            navigationContext.Parameters.TryGetValue("params", out _navParamType);

            // 延迟一下, 不然因为表格没准备好无法触发刷新
            await Task.Delay(600);

            FetchOptions.RequestRefresh(true);
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return false;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {

        }
    }
}
